<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/4/1
 * Time: 9:56
 */

/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/19
 * Time: 17:07
 */

namespace app\merchant\controller;

use app\home\model\AmountLog;
use app\home\model\IntegralLog;
use app\home\model\UserCommission;
use app\merchant\model\PackageOrder;
use app\Request;

class User
{

    public function userList(Request $request)
    {
        $param = $request->param();
        $userModel = new \app\home\model\User();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['status', 'in', [1, 0]];
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['phone|wachat_nickname', 'like', '%' . $param['name'] . '%'];
        }
        $field = 'id';
        $order = 'desc';
        if (isset($param['order_field']) && !empty($param['order_field'])) {
            $field = $param['order_field'];
        }
        $userList = $userModel
            ->where($where)
            ->field('id,wachat_nickname,status,nickname,phone,avatar,balance,integral,surplus_integral,consumption_amount,total_commission,surplus_commission,create_time,pid')
            ->limit($start, $limit)->order($field, $order)->select()->toArray();
        $count = $userModel->where($where)->count();
        $uidArray = array_column($userList, 'id');
        $pid = array_column($userList, 'pid');
        $userPidById = [];
        $userPidList = $userModel
            ->where('id', 'in', $pid)
            ->field('id,wachat_nickname,nickname,phone,avatar')
            ->select()->toArray();
        if ($userPidList) {
            $userPidById = array_column($userPidList, null, 'id');
        }

        $packageOrderModel = new PackageOrder();
        $packageOrderList = $packageOrderModel->where('uid', 'in', $uidArray)
            ->field('uid,sum(price) as price,count(uid) as count')->group('uid')->select()->toArray();
        $packageOrderListByUid = [];
        if ($packageOrderList) {
            $packageOrderListByUid = array_column($packageOrderList, null, 'uid');
        }
        foreach ($userList as $key => $value) {
            if (array_key_exists($value['id'], $packageOrderListByUid)) {
                $userList[$key]['package_amount'] = $packageOrderListByUid[$value['id']]['price'];
                $userList[$key]['package_count'] = $packageOrderListByUid[$value['id']]['count'];
            } else {
                $userList[$key]['package_amount'] = 0;
            }
            if (array_key_exists($value['pid'], $userPidById)) {
                $userList[$key]['p_wachat_nickname'] = $userPidById[$value['pid']]['wachat_nickname'];
                $userList[$key]['p_phone'] = $userPidById[$value['pid']]['phone'];
                $userList[$key]['p_nickname'] = $userPidById[$value['pid']]['nickname'];
                $userList[$key]['p_avatar'] = $userPidById[$value['pid']]['avatar'];
            }

        }

        return success('用户列表', ['list' => $userList, 'count' => $count]);
    }

    public function delUser(Request $request)
    {
        $param = $request->param();
        $useModel = new \app\home\model\User();
        $useModel->where(['id' => $param['id']])->update(['status' => $param['status']]);
        return success('操作成功');
    }

    public function commission(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['id']) && !empty($param['id'])){
            $where = ['receive_uid' => $param['id']];
        }
        if (isset($param['name']) && !empty($param['name'])){
            if (isset($param['name']) && !empty($param['name'])) {
                $Userwhere[] = ['phone|wachat_nickname|nickname', 'like', '%' . $param['name'] . '%'];
            }
            $User  =  new \app\home\model\User();
            $UserData  = $User->where($where)->select()->toArray();
            if ($UserData){
                if (isset($param['id']) && !empty($param['id'])){
                    $where[] = ['receive_uid' ,'in', $param['id']];
                }
            }
        }
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $userCommission = new UserCommission();
        $list = $userCommission
            ->limit($start, $limit)
            ->order('create_time','desc')
            ->order('create_time','desc')
            ->where($where)
            ->select();
        $count = $userCommission->where(['receive_uid' => $param['id']])->count();
        return success('佣金列表', ['list' => $list, 'count' => $count]);
    }

    public function userIntegral(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $integralLog = new IntegralLog();
        $list = $integralLog
            ->limit($start, $limit)
            ->order('create_time','desc')
            ->where(['uid' => $param['id']])
            ->select();
        $count = $integralLog->where(['uid' => $param['id']])->count();
        return success('积分', ['list' => $list, 'count' => $count]);
    }

    public function setAmount(Request $request)
    {
        $param = $request->param();
        $userModel = new \app\home\model\User();
        if ($param['type'] == 1) {
            if (isset($param['balance']) && !empty($param['balance'])) {
                $userModel->where(['id' => $param['id']])->inc('balance', $param['balance'])->update();
                $amountModel = new AmountLog();
                $amountModel->insert([
                    'uid' => $param['id'],
                    'staff_id' => $request->staff_account['id'],
                    'amount' => $param['balance'],
                    'create_time' => time(),
                    'pay_method' => 4,
                    'operate_type' => 1,
                    'pay_type' => 4,

                    'type' => 1,
                ]);
            }
            if (isset($param['integral']) && !empty($param['integral'])) {
                $userModel->where(['id' => $param['id']])
                    ->inc('integral', $param['integral'])
                    ->inc('surplus_integral', $param['integral'])
                    ->update();
                $integralLogData = [ // 积分变化
                    'num' => $param['integral'],
                    'deduction_ratio' => 0,
                    'type' => 1,
                    'mode_type' => 6,
                    'create_time' => time(),
                    'uid' => $param['id'],
                ];
                $integralLogModel = new IntegralLog();
                $integralLogModel->insert($integralLogData);
            }
            if (isset($param['commission']) && !empty($param['commission'])) {
                $userModel->where(['id' => $param['id']])
                    ->inc('total_commission', $param['commission'])
                    ->inc('surplus_commission', $param['commission'])
                    ->update();
                $userCommissionModel = new UserCommission();
                $userCommissionModel->insert([
                    'trigger_uid' => 0,
                    'receive_uid' => $param['id'],
                    'level' => 0,
                    'amount' => $param['commission'],
                    'ratio' => 0,
                    'type' => 1,
                ]);
            }
        } else {
            if (isset($param['balance']) && !empty($param['balance'])) {
                $userModel->where(['id' => $param['id']])->dec('balance', $param['balance'])->update();
                $amountModel = new AmountLog();
                $amountModel->insert([
                    'uid' => $param['id'],
                    'staff_id' => $request->staff_account['id'],
                    'amount' => $param['balance'],
                    'create_time' => time(),
                    'pay_method' => 4,
                    'operate_type' => 1,
                    'pay_type' => 4,
                    'type' => 2,
                ]);
            }
            if (isset($param['integral']) && !empty($param['integral'])) {
                $userModel->where(['id' => $param['id']])
                    ->dec('integral', $param['integral'])
                    ->dec('surplus_integral', $param['integral'])
                    ->update();
                $integralLogData = [ // 积分变化
                    'num' => $param['integral'],
                    'deduction_ratio' => 0,
                    'type' => 2,
                    'mode_type' => 6,
                    'create_time' => time(),
                    'uid' => $param['id'],
                ];
                $integralLogModel = new IntegralLog();
                $integralLogModel->insert($integralLogData);
            }
            if (isset($param['commission']) && !empty($param['commission'])) {
                $userModel->where(['id' => $param['id']])
                    ->dec('total_commission', $param['commission'])
                    ->dec('surplus_commission', $param['commission'])
                    ->update();

                $userCommissionModel = new UserCommission();
                $userCommissionModel->insert([
                    'trigger_uid' => 0,
                    'receive_uid' => $param['id'],
                    'level' => 0,
                    'amount' => -$param['commission'],
                    'ratio' => 0,
                    'type' => 2,
                ]);
            }
        }
        return success('修改成功');
    }

    public function setTopUser(Request $request)
    {
        $param = $request->param();
        $userModel = new \app\home\model\User();
        $topUser = $userModel->where(['id' => $param['top_id']])->find();
        $userModel->where(['id' => $param['id']])
            ->update(['pid' => $param['top_id'], 'pids' => $topUser['pids'] . ',' . $param['top_id']]);
        return success('修改成功');
    }

    public function UserInfo(Request $request){
        $param = $request->param();
        $userModel = new \app\home\model\User();
        $userInfo = $userModel
            ->where(['id' => $param['uid']])->find();
        return adminSuccess('用户详情',$userInfo);

    }



    public function balance(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where= [];
        $AmountLog = new AmountLog();
        if (isset($param['type']) && !empty($param['type'])){
            $where[]= ['type','=',$param['type']];
        }
        if (isset($param['id']) && !empty($param['id'])){
            $where[]= ['uid','=',$param['id']];
        }
        if (isset($param['start_time']) && !empty($param['start_time'])){
            $where[]= ['create_time','>=',strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])){
            $where[]= ['create_time','<=',strtotime($param['end_time'])];
        }
        $list = $AmountLog
            ->limit($start, $limit)
            ->order('create_time','desc')
            ->where($where)
            ->select();

        $count = $AmountLog
            ->where($where)->count();
        return success('余额', ['list' => $list, 'count' => $count]);
    }
}